package timing.ukulele.third.controller.common;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import timing.ukulele.common.data.ResponseData;
import timing.ukulele.facade.third.mvc.ThirdCommonControllerFacade;
import timing.ukulele.third.controller.msg.AliyunMessageTemplateController;
import timing.ukulele.third.controller.weixin.WxMessageTemplateController;
import timing.ukulele.third.dictionary.msg.MsgChannelType;
import timing.ukulele.third.persistent.msg.ChannelAccount;
import timing.ukulele.third.service.common.ThirdCommonService;
import timing.ukulele.third.service.msg.ChannelAccountService;

/**
 * 第三方通用controller，用于内部其他业务系统调用第三方服务
 * @author zh
 */
@RestController
@Slf4j
@AllArgsConstructor
public class ThirdCommonController implements ThirdCommonControllerFacade {

    private final ThirdCommonService thirdCommonService;

    private final ChannelAccountService channelAccountService;

    private final WxMessageTemplateController wxMessageTemplateController;

    private final AliyunMessageTemplateController aliyunMessageTemplateController;

    /**
     * 根据/thirdType/appid/code获取第三方平台用户唯一标识
     * @param appId
     * @param code
     * @return
     */
    @Override
    public ResponseData<String> getPlatIdByCode(Integer thirdType, String appId, String code) {
        try {
            return ResponseData.success(thirdCommonService.getPlatIdByCode(thirdType, appId, code));
        } catch (WxErrorException e) {
            return ResponseData.error("根据/thirdType/appid/code获取第三方平台用户唯一标识失败"+e.getMessage());
        }
    }

    /**
     * 根据账号获取渠道模板列表数据
     * @param accountId
     * @param sysTemplateId
     * @return
     */
    @GetMapping("/template/getThirdTemplateList")
    public ResponseData getThirdTemplateList(@RequestParam("accountId") Long accountId,
                                             @RequestParam(value = "sysTemplateId", required = false) Long sysTemplateId) {
        ChannelAccount channelAccount = channelAccountService.getById(accountId);
        if(MsgChannelType.OFFICIAL_ACCOUNT.getCode().equals(channelAccount.getSendChannel())) {
            return wxMessageTemplateController.getWxToSysMsgTemplateList(accountId, sysTemplateId);
        } else if (MsgChannelType.ALYSms.getCode().equals(channelAccount.getSendChannel())) {
            return aliyunMessageTemplateController.getAliyunToSysMsgTemplateList(accountId, sysTemplateId);
        }else {
            return ResponseData.error("暂不支持的渠道查询！");
        }
    }

}
